<script lang="tsx">
/**
 * 图片上传
 */
export default {
  name: "yy-img-upload"
}
</script>

<script lang="tsx" setup>
import {UploadFile, UploadFiles, UploadProps} from "element-plus"
import {Plus} from "@element-plus/icons-vue"
import {ref, watch} from "vue"
import {globalSetting} from "../../../config/global-setting.ts"
import {YyImgUploadCustomerEvents, YyImgUploadCustomerProps} from "./index.ts"

/**
 * 定义emit
 */
const emit: any = defineEmits<YyImgUploadCustomerEvents>()

/**
 * 定义props
 */
interface YyImgUploadProps {
  modelValue: string,
  props?: YyImgUploadCustomerProps
}

const props = withDefaults(defineProps<YyImgUploadProps>(), {
  props: () => ({
    listType: 'picture-card',
    action: "/api/upload",
    limit: 1,
    segment: ","
  })
})

/**
 * 图片数据
 */
const imgData = ref()

/**
 * 初始化数据
 */
const initData = (imgValue: string) => {
  if (!imgValue) {
    imgData.value = []
    return
  }

  imgData.value = imgValue.split(props.props.segment || ',').map((item: string, index: number) => {
    return {
      index: index + 1,
      url: item
    }
  })
}

/**
 * 删除
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  emit("remove", uploadFile, uploadFiles)
}

/**
 * 弹窗
 */
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  emit("preview", uploadFile)
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

/**
 * 上传成功回调
 */
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  const value = uploadFiles.map((item: any) => {
    if (item.index) {
      return item.url
    } else {
      return globalSetting.fileUrl + item.response
    }
  }).join(props.props.segment || ",")
  emit("change", value)
}

/**
 * 监听
 */
watch(() => props.modelValue, (newValue) => {
  if (newValue !== undefined && newValue !== null) {
    initData(newValue)
  }
}, {
  deep: true,
  immediate: true
})

// 同时监视props的变化，确保组件响应式更新
watch(
    () => props.props,
    () => {
      initData(props.modelValue || "")
    },
    {deep: true}
)
</script>

<template>
  <div class="yy-img-upload">
    <el-upload
        v-model:file-list="imgData"
        :action="globalSetting.proxyUrl + (props.props.action || '/api/upload')"
        :limit="props.props.limit"
        :list-type="props.props.listType"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
    >
      <el-icon v-if="props.props.listType === 'picture-card'">
        <Plus/>
      </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img :src="dialogImageUrl" alt="Preview Image" w-full/>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>

</style>